package com.ssi.myshop.Presenter.impl;

import android.util.Log;

import com.ssi.myshop.Presenter.ICategoryPresenter;
import com.ssi.myshop.base.BaseListData;
import com.ssi.myshop.base.BaseListObserver;
import com.ssi.myshop.bean.CategoryBean;
import com.ssi.myshop.bean.CategoryContentBean;
import com.ssi.myshop.contants.Api;
import com.ssi.myshop.utils.RetrofitManager;
import com.ssi.myshop.utils.RxUtil;
import com.ssi.myshop.view.ICategoryCallBack;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import retrofit2.Retrofit;

public class ICategoryPresenterImpl implements ICategoryPresenter {
    private static final String TAG = "ICategoryPresenterImpl";

    ICategoryCallBack mCallBack;
    private Retrofit mRetrofit;
    private Api mApi;

    @Override
    public void getCategory() {
        mRetrofit = RetrofitManager.getInstance().getRetrofit();
        mApi = mRetrofit.create(Api.class);
        Observable<BaseListData<CategoryBean>> observable = mApi.getCategory();
        observable.compose(RxUtil.schedulerTransformer()).subscribeWith(new BaseListObserver<CategoryBean>(mCallBack) {
            @Override
            protected void onSuccess(List<CategoryBean> data) {
                mCallBack.onCategoryLoad(data);
            }
        });
    }

    @Override
    public void getContentByCategoryId(CategoryBean category) {
        Log.d(TAG, "categoryID: " + category.getId());
        int categoryId = category.getId();
        Observable<BaseListData<CategoryContentBean>> observable = mApi.getCategoryContent();
        List<CategoryContentBean> datas = new ArrayList<>();
        observable.compose(RxUtil.schedulerTransformer()).subscribeWith(new BaseListObserver<CategoryContentBean>(mCallBack) {
            @Override
            protected void onSuccess(List<CategoryContentBean> data) {
                Log.d(TAG, "onSuccess: "+data.toString());
                for (CategoryContentBean bean: data) {
                    if (bean.getCategoryId() == categoryId){
                        datas.add(bean);
                    }
                }
                mCallBack.onContentLoad(datas);
            }
        });
    }

    @Override
    public void registerViewCallBack(ICategoryCallBack callBack) {
        this.mCallBack = callBack;
    }

    @Override
    public void unregisterViewCallBack(ICategoryCallBack callBack) {
        if (mCallBack != null) {
            mCallBack = null;
        }
    }
}
